package com.czk.netty.nio.chat;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Scanner;
import java.util.Set;
import java.util.concurrent.TimeUnit;

/**
 * nio聊天系统的客户端
 *
 * @Author:ChenZhangKun
 * @Date: 2021/1/12 21:14
 */
public class GroupChatClient {
    /**
     * 服务器ip
     */
    private final String HOST = "127.0.0.1";
    /**
     * 端口
     */
    private final int PORT = 6667;
    private Selector selector;
    private SocketChannel socketChannel;
    /**
     * 用户名
     */
    private String username;

    public GroupChatClient() {
        try {
            // 初始化选择器
            selector = Selector.open();
            // 连接服务器
            socketChannel = SocketChannel.open();
            socketChannel.connect(new InetSocketAddress(HOST, PORT));
            // 配置非阻塞
            socketChannel.configureBlocking(false);
            // 注册到selector
            socketChannel.register(selector, SelectionKey.OP_READ);
            // 拿到用户名
            username = socketChannel.getLocalAddress().toString().substring(1);
            System.out.println(username + "准备好了");
        } catch (Exception ex) {

        }

    }

    /**
     * 发送消息
     *
     * @param info
     */
    public void sendInfo(String info) {
        info = username + " 说 " + info;
        try {
            socketChannel.write(ByteBuffer.wrap(info.getBytes()));
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

    /**
     * 读取服务器写回的消息
     */
    public void readInfo() {
        try {
            int select = selector.select();
            if (select > 0) {
                // 拿到注册的通道
                Set<SelectionKey> selectionKeys = selector.selectedKeys();
                Iterator<SelectionKey> iterator = selectionKeys.iterator();
                while (iterator.hasNext()) {
                    // 拿到通道
                    SelectionKey selectionKey = iterator.next();
                    // 判断状态
                    if (selectionKey.isReadable()) {
                        // 拿到相关通道
                        SocketChannel channel = (SocketChannel) selectionKey.channel();
                        socketChannel.configureBlocking(false);
                        ByteBuffer buffer = ByteBuffer.allocate(1024);
                        // 读取数据
                        channel.read(buffer);
                        // 转成字符安
                        String message = new String(buffer.array());
                        System.out.println(message.trim());
                    }
                }
                iterator.remove();
            } else {
               // System.out.println("没有可用的通道");
            }
        } catch (Exception ex) {

        }
    }

    public static void main(String[] args) throws Exception {
        // 开启客户端
        GroupChatClient client = new GroupChatClient();
        // 开启一个线程读取消息
        new Thread(() -> {
            while (true) {
                client.readInfo();
                // 线程休眠
                try {
                    TimeUnit.SECONDS.sleep(3);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }).start();
        // 开启线程发送消息
        Scanner scanner = new Scanner(System.in);
        // 读取下一行
        while (scanner.hasNext()) {
            String next = scanner.next();
            client.sendInfo(next);
        }
    }
}